<template>
  <Box class="___basic-table-container">
    <div ref="tableContainerRef" style="width: 100%; height: 100%">
      <el-table
        ref="tableDataRef"
        class="table-width"
        :max-height="tableMaxHeight"
        :style="{ width: `${tableMaxWidth}px` }"
        :data="tableData"
        :stripe="false"
        :row-class-name="rowClassName"
        header-row-class-name="__header-row-class-name"
        cell-class-name="__cell-class-name"
        border
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
      >
        <!-- <template #empty>
          <el-empty description="暂无数据" />
        </template> -->
        <el-table-column v-if="indexFlag" type="index" width="50" label="#" />
        <el-table-column v-if="selectionFlag" type="selection" width="55" align="center" />
        <el-table-column
          v-for="item in columns"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label"
          :min-width="item.width"
          :align="item.align || 'center'"
          :formatter="item.formatter"
          :sortable="item.sortable"
          :sort-method="item.sortMethod ? (a, b) => handleSort(a, b, item) : undefined"
          show-overflow-tooltip
          header-align="center"
        />

        <el-table-column
          v-if="operationFlag"
          label="操作"
          :width="operationWidth"
          header-align="center"
          :fixed="operationFixed ? 'right' : ''"
        >
          <template #default="{ row }">
            <div style="display: flex; justify-content: center; gap: 8px">
              <!-- 新增居中样式 -->
              <el-button v-if="editFlag" type="primary" :icon="Edit" circle @click="editFun(row)" />
              <el-popconfirm v-if="deleteFlag" title="确定删除吗?" @confirm="deleteFun(row)">
                <template #reference>
                  <el-button type="danger" :icon="Delete" circle />
                </template>
              </el-popconfirm>
              <slot name="operation" :row="row" />
            </div>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-if="paginationEnabled && (pagination.total ?? 0) > 0"
        class="pagination"
        :current-page="pagination.pageNo"
        :page-sizes="pagination.pageSizesArr"
        :page-size="pagination.pageSize"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
      />
    </div>
  </Box>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, nextTick, onBeforeUnmount } from 'vue'
import { ElTable } from 'element-plus'
import Box from '@/components/Box/Index.vue'
import type { PropType } from 'vue'
import type { PaginationConfig } from '@/api/modules/Analyzer/Common/types'
import { Delete, Edit } from '@element-plus/icons-vue'

// 完善类型定义
export interface Column {
  prop: string
  label: string
  width?: number | string
  align?: 'left' | 'center' | 'right'
  formatter?: (row: any, column: any, cellValue: any, index: number) => any
  sortable?: boolean | 'custom'
  // 排序方法：接收两个行数据，返回排序结果（-1/0/1）
  sortMethod?: (a: any, b: any) => number
}

const props = defineProps({
  tableData: {
    type: Array as () => Array<any>,
    default: () => [
      {
        name: '示例数据',
      },
    ],
  },
  pageConfig: {
    type: [Object, Boolean] as PropType<PaginationConfig | boolean>,
    default: false,
  },
  selectionFlag: {
    type: Boolean,
    default: false,
  },
  columns: {
    type: Array as () => Array<Column>,
    default: () => [
      {
        prop: 'name',
        label: '列名称',
        width: '180',
      },
    ],
  },
  operationFlag: {
    type: Boolean,
    default: false,
  },
  operationWidth: {
    type: [Number, String] as PropType<number | string>,
    default: 200,
  },
  operationFixed: {
    type: Boolean,
    default: false,
  },
  deleteFlag: {
    type: Boolean,
    default: true,
  },
  editFlag: {
    type: Boolean,
    default: true,
  },
  selectedRowIndex: {
    type: Number,
    default: undefined,
  },
  indexFlag: {
    type: Boolean,
    default: false,
  },
  loading: {
    type: Boolean,
    default: false,
  },
})

// 定义emits类型
const emits = defineEmits<{
  (e: 'rowClick', row: any, index: number): void
  (e: 'updatePageConfig', config: PaginationConfig): void
  (e: 'selectionChange', selection: any[]): void
  (e: 'deleteFun', row: any): void
  (e: 'editFun', row: any): void
}>()

// 响应式数据
const tableContainerRef = ref<HTMLElement | null>(null)
const tableDataRef = ref<InstanceType<typeof ElTable> | null>(null)
const tableMaxHeight = ref(0)
const tableMaxWidth = ref(0)
const resizeObserver = ref<ResizeObserver | null>(null)

// 计算属性
const paginationEnabled = computed(() => props.pageConfig !== false)

const pagination = computed<PaginationConfig>(() => {
  if (!paginationEnabled.value) {
    return { pageNo: 1, pageSize: 20, total: 0 }
  }

  // 确保只在pageConfig为对象类型时访问其属性
  const config = props.pageConfig as PaginationConfig

  return {
    pageNo: config.pageNo ?? 1,
    pageSize: config.pageSize ?? 20,
    pageSizesArr: config.pageSizesArr ?? [20, 50, 100, 200],
    total: config.total ?? 0,
  }
})

// 处理排序逻辑的包装函数
const handleSort = (a: any, b: any, column: Column) => {
  if (typeof column.sortMethod === 'function') {
    try {
      // 调用用户定义的排序方法
      return column.sortMethod(a, b)
    } catch (error) {
      console.error(`列 ${column.prop} 的排序方法执行出错:`, error)
    }
  }
  // 默认排序逻辑（按列的prop值比较）
  const valueA = a[column.prop]
  const valueB = b[column.prop]

  // 处理特殊类型（如数字、字符串、日期）
  if (typeof valueA === 'number' && typeof valueB === 'number') {
    return valueA - valueB
  }
  if (valueA instanceof Date && valueB instanceof Date) {
    return valueA.getTime() - valueB.getTime()
  }
  // 字符串默认按localeCompare排序
  return String(valueA).localeCompare(String(valueB))
}

// 方法
const calculateTableDimensions = () => {
  if (!tableContainerRef.value) return

  const containerHeight = tableContainerRef.value.offsetHeight
  const containerWidth = tableContainerRef.value.offsetWidth

  tableMaxWidth.value = containerWidth

  // 计算表格高度，减去分页组件高度
  const paginationHeight = paginationEnabled.value ? 60 : 0
  tableMaxHeight.value = containerHeight - paginationHeight
}

const handleSelectionChange = (selection: any[]) => {
  emits('selectionChange', selection)
}

const handleRowClick = (row: any, column: any, event: MouseEvent, index: number) => {
  emits('rowClick', row, index)
}

const handlePageChange = (page: number) => {
  if (!paginationEnabled.value) return

  emits('updatePageConfig', {
    ...pagination.value,
    pageNo: page,
  })
}

const handleSizeChange = (pageSize: number) => {
  if (!paginationEnabled.value) return

  emits('updatePageConfig', {
    ...pagination.value,
    pageNo: 1, // 切换每页数量时重置为第一页
    pageSize: pageSize,
  })
}

const deleteFun = (row: object) => {
  emits('deleteFun', row)
}
const editFun = (row: object) => {
  emits('editFun', row)
}

const rowClassName = ({ rowIndex }: { rowIndex: number }) => {
  // 添加行索引
  // row._index = rowIndex

  // 高亮选中行
  if (props.selectedRowIndex !== undefined && props.selectedRowIndex === rowIndex) {
    return '__row-class-name selected-row'
  }

  // 隔行变色
  return '__row-class-name'
}
// 生命周期钩子
onMounted(() => {
  calculateTableDimensions()

  // 添加ResizeObserver监听容器尺寸变化
  if (tableContainerRef.value) {
    resizeObserver.value = new ResizeObserver(() => {
      calculateTableDimensions()
    })
    resizeObserver.value.observe(tableContainerRef.value)
  }
})

onBeforeUnmount(() => {
  // 清理ResizeObserver
  if (resizeObserver.value) {
    resizeObserver.value.disconnect()
    resizeObserver.value = null
  }
})

// 监听数据变化
watch(
  [() => props.tableData.length, () => props.pageConfig],
  () => {
    nextTick(() => {
      calculateTableDimensions()
    })
  },
  { immediate: true },
)
</script>

<style lang="scss" scoped>
.___basic-table-container {
  display: flex;
  flex-direction: column;
  padding: 16px;

  // .table-width {
  //   border-radius: 10px 10px 0 0;
  //   // 选中行样式
  //   .selected-row {
  //     background-color: #165cc4 !important;
  //   }
  //   :deep(.el-table__inner-wrapper::before) {
  //     background-color: #0c2879;
  //   }
  //   :deep(.el-table__inner-wrapper) {
  //     .el-table__header-wrapper {
  //       // outline: 2px solid #409dff;
  //       border-radius: 10px 10px 0 0;
  //       border: 2px solid #409dff;
  //       background-color: #0b3678;
  //       .__header-row-class-name {
  //         background-color: #0b3678;
  //         box-shadow: inset 0px -6px 32px 0px #1b89ff;
  //         // outline: 2px solid #409dff;
  //         // border: 2px solid #409dff;

  //         .el-table__cell {
  //           background-color: transparent;
  //           border-bottom: none;
  //         }
  //       }
  //     }
  //     .el-table__body-wrapper {
  //       .__row-class-name {
  //         background-color: #0b48a3;
  //         //
  //         .__cell-class-name {
  //           border-bottom: 2px solid #0c2879;
  //         }
  //       }
  //     }
  //   }
  // }
  // .pagination {
  //   display: flex;
  //   justify-content: flex-end;
  //   background-color: #0b48a3;
  //   padding: 10px 10px;
  //   border-radius: 0 0 10px 10px;
  //   :deep(.el-select__wrapper) {
  //     background-color: #0b48a3;
  //     box-shadow: 0 0 0 1px #409dff inset;
  //   }
  // }
}
</style>
